const user = require("../models/userDetail")
const verifyCode = require("../models/verifyCode")

var express = require('express');
var router = express.Router();

const formidable = require('formidable');

router.post('/', (req, res, next) => {
  var form = new formidable.IncomingForm();
    form.parse(req, async function (err, fields, files) {
      if(err){
        res.json({ 'state': false })
      } else {
        try{
          let user_data = await user.find({
            UUID: fields.UUID
          })
          if(user_data.length===0){
            res.json({
              state: false,
              msg: '该用户信息不存在'
            })
            return;
          }
          if(user_data[0].password!==fields.password){
            res.json({
              state: false,
              msg: '密码错误！'
            })
            return;
          } 
          let res_veri = await verifyCode.find({
              code: fields.code,
              email: fields.email
          })
          if(res_veri.length===0){
              res.json({
                  state: false,
                  msg: '验证码错误！'
              })
              return;
          }
          await verifyCode.deleteMany({email: fields.email})
          
          let return_data = await user.findOneAndUpdate({ 'UUID': fields.UUID }, {
            $set: {
                email: fields.email
            }
          }, { new: true })
          res.json({
            state: true,
            data: return_data
          })
        } catch(err){
          console.log(err)
          res.json({
            state: false,
            msg: '绑定邮箱失败'
          })
        }
      }
    })
})

module.exports = router;